package com.yunfangdata.service.impl;

import com.yunfangdata.domain.Permission;
import com.yunfangdata.domain.Role;
import com.yunfangdata.mapper.RoleMapper;
import com.yunfangdata.query.QueryObject;
import com.yunfangdata.service.IRoleService;
import com.yunfangdata.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {


    @Autowired
    private RoleMapper mapper;

    public void save(Role entity) {
        mapper.insert(entity);

        List<Permission> permissions = entity.getPermissions();
        if (permissions.size()>0){
            //保存角色 与 权限关系
            for (Permission permission : permissions) {
                mapper.saveRoleAndPermissionRelation(entity.getId(),permission.getId());
            }
        }

    }

    public void delete(Long id) {
        //删除角色 与 权限关系
        mapper.deleteRoleAndPermissionRelation(id);

        mapper.deleteByPrimaryKey(id);
    }

    public void update(Role entity) {


        mapper.updateByPrimaryKey(entity);
        //删除角色 与 权限关系
        mapper.deleteRoleAndPermissionRelation(entity.getId());

        List<Permission> permissions = entity.getPermissions();
        if (permissions.size()>0){
            //保存角色 与 权限关系
            for (Permission permission : permissions) {
                mapper.saveRoleAndPermissionRelation(entity.getId(),permission.getId());
            }
        }


    }


    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Role> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);

        if (total == 0){
            return new PageResult();
        }
        List<Role> rows = mapper.queryForList(qo);
        return new PageResult(total,rows);
    }

    public List<Role> queryEmpForRoles(Long empId) {
        if (mapper.queryEmpForRoles(empId) == null) {
            return new ArrayList<>();
        }
            return mapper.queryEmpForRoles(empId);
    }

}
